package cn.easyutil.veteran.core.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.lang.NonNull;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;

public class SpringUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
        SpringUtils.applicationContext = applicationContext;
    }

    public static <T>T getBean(String beanName){
        if(applicationContext == null){
            return null;
        }
        try {
            return (T) applicationContext.getBean(beanName);
        }catch(Exception e){
            return null;
        }
    }

    public static <T>T getBean(Class<T> beanClass){
        if(applicationContext == null){
            return null;
        }
        try {
            return applicationContext.getBean(beanClass);
        }catch(Exception e){
            return null;
        }

    }

    public static <T> Collection<T> getBeansOfType(Class<T> beanClass){
        if(applicationContext == null){
            return null;
        }
        try {
            Map<String, T> beansOfType = applicationContext.getBeansOfType(beanClass);
            if(CollectionUtils.isEmpty(beansOfType)){
                return Collections.emptyList();
            }
            return beansOfType.values();
        }catch (Exception e){
            return new ArrayList<>();
        }
    }
}
